package de.slothsoft.android4swing;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Scanner;

final class AndroidResourceReader {

    private static final String BUNDLE_EXTENSION = ".xml";
    private static final String BUNDLE_I18N = "{0}-{1}";
    private static final String PATH_SEPARATOR_REGEX = "[/\\\\]{1}";
    private static final String PATH_SEPARATOR = "/";

    public static String readBaseBundle(String bundlePath) throws IOException {
	InputStream in = getStream(bundlePath + BUNDLE_EXTENSION);
	if (in == null)
	    return null;
	return doReadBundle(in);
    }

    public static String readBundle(String bundlePath, Locale locale) throws IOException {
	String bundleFileName = getBundleFileName(bundlePath, locale);
	if (bundleFileName == null)
	    return null;
	InputStream in = getStream(bundleFileName + BUNDLE_EXTENSION);
	if (in == null)
	    return null;
	return doReadBundle(in);
    }

    @SuppressWarnings("resource")
    protected static String doReadBundle(InputStream in) throws IOException {
	return new Scanner(in, "UTF-8").useDelimiter("\\A").next(); //$NON-NLS-1$ //$NON-NLS-2$
    }

    protected static String getBundleFileName(String bundlePath, Locale locale) {
	String[] bundlePathSplit = bundlePath.split(PATH_SEPARATOR_REGEX);
	if (bundlePathSplit.length < 2)
	    return null;
	int bundleFolderIndex = bundlePathSplit.length - 2;
	bundlePathSplit[bundleFolderIndex] = MessageFormat.format(BUNDLE_I18N, bundlePathSplit[bundleFolderIndex],
		locale.getLanguage());
	StringBuilder localizedBundlePath = new StringBuilder();
	for (String split : bundlePathSplit) {
	    if (localizedBundlePath.length() > 0) {
		localizedBundlePath.append(PATH_SEPARATOR);
	    }
	    localizedBundlePath.append(split);
	}
	return localizedBundlePath.toString();
    }

    private static InputStream getStream(String bundle) throws IOException {
	return AndroidResourceReader.class.getClassLoader().getResourceAsStream(bundle);
    }

    private AndroidResourceReader() {
	// hide util class
    }

}